<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--  -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!--  -->
      <el-table :data="rolelist" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['vcenter','bdbottom',i==0?'bdtop':'']"
              v-for="(item,i) in scope.row.children"
              :key="item.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item.id)">{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级、三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环渲染二级权限 -->
                <el-row
                  :class="[i2==0? '':'bdtop','vcenter']"
                  v-for="(item2,i2) in item.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning"
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      @close="removeRightById(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{scope.row}}</pre> -->
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <el-button
              @click="showRightDialog(scope.row)"
              type="warning"
              icon="el-icon-setting"
              size="mini"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog @close="setRightDialogClosed" title="分配权限" :visible.sync="setRightDialogVisible" width="30%">
      <el-tree ref="treeRef" :default-checked-keys="defkeys" default-expand-all node-key="id" show-checkbox :data="rightslist" :props="treeProps"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 所有角色列表数据
      rolelist: [],
      setRightDialogVisible:false,
      rightslist:[],
      treeProps:{
          label:'authName',
          children:'children'
      },
      defkeys:[],
      roleId:''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    //获取所有角色数据
    async getRolesList() {
      const { data: res } = await this.$axios.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.rolelist = res.data
      //console.log(this.rolelist)
    },
    // 根据id删除权限标签
    async removeRightById(role, id) {
      // 弹框提示是否删除
      const confirmResult = await this.$confirm('是否删除此权限', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$axios.delete(
        `roles/${role.id}/rights/${id}`
      )
      if (res.meta.status !== 200) {
        this.$message.error('删除权限失败')
      }
      this.$message.success(res.meta.msg)
      // 不建议使用这个。因为会导致页面的折叠
      // this.getRolesList();
      role.children = res.data
    },
    // 展示分配权限对话框
    async showRightDialog(role) {
        this.roleId = role.id
        // 获取数据
        const {data:res} = await this.$axios.get('rights/tree');
        if(res.meta.status!==200){
            return this.$message.error('获取权限数据失败')
        }
        this.rightslist = res.data;
        //console.log(this.rightslist)
        // 递归获取三级节点的id
        this.getLeafKeys(role,this.defkeys)
        this.setRightDialogVisible = true;
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到defkeys数组中
    getLeafKeys(node,arr){
        // 如果当前node 节点不包含children属性，则是三级节点
        if(!node.children){
            return arr.push(node.id)
        }
        node.children.forEach(item=>{
            this.getLeafKeys(item,arr)
        })
    },
    setRightDialogClosed(){
        this.defkeys = [];
    },
    async allotRights(){
       const keys = [
           ...this.$refs.treeRef.getCheckedKeys(),
           ...this.$refs.treeRef.getHalfCheckedKeys(),
        ] 
        const idStr = keys.join(',')
        const {data:res} = await this.$axios.post(`roles/${this.roleId}/rights`,{rids:idStr})
        if(res.meta.status!==200){
            return this.$message.error('分配权限失败')
        }
        this.$message.success(res.meta.msg)
        this.getRolesList();
        this.setRightDialogVisible = false;
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 15px;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>